import http from './http'

function deepGet(obj, path){ if(!path) return obj; return path.split('.').filter(Boolean).reduce((a,k)=>a&&a[k]!==undefined?a[k]:undefined,obj) }
function pickFirst(obj, keys){ for(const k of keys){ if(obj[k]!==undefined&&obj[k]!==null) return obj[k] } return undefined }
function normalize(val){ return val===undefined||val===null?val:String(val) }

const API = {
  list: '/roles',
  add: '/roles',
  update: '/roles', // PUT，id 在 body
  remove: (id)=>`/roles/${id}`,
  getById: (id)=>`/roles/${id}`,
  resp: { root:'', listKey:'rows', totalKey:'total' },
  itemMap: {
    id:['id'], name:['name'], label:['label'], remark:['remark'],
    updatedAt:['update_time','updateTime'], createdAt:['create_time','createTime']
  }
}

function normalizeItem(o){
  return {
    id: pickFirst(o, API.itemMap.id),
    name: pickFirst(o, API.itemMap.name),
    label: pickFirst(o, API.itemMap.label),
    remark: pickFirst(o, API.itemMap.remark),
    updatedAt: pickFirst(o, API.itemMap.updatedAt),
    createdAt: pickFirst(o, API.itemMap.createdAt)
  }
}

export async function listRoles(params){
  const req = { page: params?.page, pageSize: params?.pageSize }
  if(params?.name!==undefined) req.name = params.name
  if(params?.label!==undefined) req.label = params.label
  const raw = await http.get(API.list, { params: req })
  const root = API.resp.root? deepGet(raw, API.resp.root): raw
  let rows=[], total=0
  if(root && typeof root==='object' && Array.isArray(root[API.resp.listKey])){
    rows = root[API.resp.listKey]; total = Number(root[API.resp.totalKey] ?? rows.length) || rows.length
  } else if(Array.isArray(raw)) { rows = raw; total = raw.length }
  return { list: rows.map(normalizeItem), total }
}

export async function addRole(payload){
  const body = { name: normalize(payload.name), label: normalize(payload.label), remark: normalize(payload.remark) }
  return http.post(API.add, body)
}

export async function updateRole(id, payload){
  const body = { id, name: normalize(payload.name), label: normalize(payload.label), remark: normalize(payload.remark) }
  return http.put(API.update, body)
}

export async function removeRole(id){ return http.delete(API.remove(id)) }
export async function getRoleById(id){ const raw = await http.get(API.getById(id)); return normalizeItem(raw) }
